import axios from 'axios'

const Auth_Success ="Auth_Success"
const Error_Msg = "Error_Msg"
const LOGIN_OUT ='LOGIN_OUT'
const LOAD_DATA ="LOAD_DATA"
const initState={
    user:'',
    pwd:'',
    time:'',
}
export function user(state=initState,action){
    switch(action.type){
        case Auth_Success:
            return { ...state, ...action.payload,isAuth:true,redirect:'/home'}
        case LOAD_DATA:
            return { ...state, ...action.payload, isAuth: true,}
        case Error_Msg:
            return { ...state, msg: action.msg, isAuth: true,}
        case LOGIN_OUT:
            return { ...initState, isAuth: false, redirect: '/login'}
        default:
            return state
        }
}
export function AuthSuccess(data){
    return { type: Auth_Success,payload:data}
}
export function errorMsg(msg){
    return { msg, type: Error_Msg}
}
export function loginOut(){
    return {type:LOGIN_OUT}
}
export function loadData(userinfo) {
    return { type: LOAD_DATA, payload: userinfo }
}
export function updata(time){
    return dispatch=>{
        axios.post('/user/updata', {time})
            .then(res => {
                if (res.status === 200 && res.data.code === 0) {
                    dispatch(AuthSuccess(res.data.data))
                } else {
                    dispatch(errorMsg(res.data.msg))
                }
            })
    }
}
export function login({user,pwd,time}){
    if (!user || !pwd){
        return  errorMsg('请输入用户名或者密码')
    }
    return dispatch=>{
        axios.post('/user/login',{user,pwd,time})
            .then(res=>{
                if(res.status===200&&res.data.code===0){
                    dispatch(AuthSuccess( res.data.data))
                }else{
                    dispatch(errorMsg(res.data.msg))
                }
            })
    }
}
export function register({user,pwd,time}){
    if (!user || !pwd) {
        return errorMsg('用户名或者密码不能为空')
    }
    return dispatch=>{
        axios.post('/user/register',{user,pwd,time})
            .then(res=>{
                if(res.status===200&&res.data.code===0){
                    dispatch(AuthSuccess({ user, pwd,time }))
                } else{
                    dispatch(errorMsg(res.data.msg))
                }
            })
    }
}